<template>
  <div class="sync-box">
    <div v-if="active > 0" class="progress">
      <p>Step {{ active }}/4</p>
      <el-progress :percentage="(100 / 4) * active" />
    </div>
    <One v-if="active == 0" ref="one" :data="form" />
    <Two v-if="active == 1" ref="two" :data="form" />
    <Three v-if="active == 2" ref="three" :data="form" />
    <Four v-if="active == 3" ref="four" :data="form" />
    <Five v-if="active == 4" ref="five" :data="form" />
    <div class="buttonBox">
      <el-button
        v-if="active > 0"
        size="medium"
        @click.prevent="handleClick('prev')"
      >上一步</el-button>
      <el-button
        type="primary"
        size="medium"
        @click.prevent="handleClick('next')"
      >{{ active == 4 ? "完成" : "下一步" }}</el-button>
    </div>
  </div>
</template>

<script>
import One from './add/one.vue'
import Two from './add/two.vue'
import Three from './add/three.vue'
import { stepOneData, stepTwoData } from './add/index'
import Four from './add/four.vue'
import Five from './add/five.vue'
import { dataTaskconfadd, dataTaskconfedit } from '@/api/console/tasks.js'
import { convertToCamelCase } from '@/utils/index.js'
import { getDataTaskconf } from '@/api/console/dataTaskconf.js'

const ignoreData = ['dsc']

const removeValue = [
  'ip',
  'pwd',
  'port',
  'uname',
  'start',
  'end',
  'baseType',
  'appraiseCountmode',
  'appraiseTaskmode',
  'cdcSwitch',
  'jobSwitch'
]
export default {
  name: 'TaskDataSync',
  dicts: ['synchronous_tasktype'],
  components: { One, Two, Three, Four, Five },
  data: function() {
    return {
      form: {},
      rules: {},
      active: 0,
      allForm: [stepOneData, stepTwoData]
    }
  },
  created() {
    const that = this
    this.$route.meta.title = this.$route.query.id
      ? '修改迁移任务'
      : '新增迁移任务'
    if (that.$route.query.id) {
      const newMapping = []
      that.id = that.$route.query.id
      getDataTaskconf({ id: that.$route.query.id }).then(async({ data }) => {
        data.taskTypeScope = data.taskTypeScope.split(',')
        data.mapping = JSON.parse(data.mapping)
        if (data.mapping) {
          Object.keys(data.mapping).forEach((f, i) => {
            if (data.mapping[f].length > 0) {
              newMapping.push(...data.mapping[f])
            }
          })
          data.mapping = newMapping
        }
        this.getDicts('synchronous_tasktype').then((res) => {
          const item = res.data.find((f) => f.dictValue === data.jobType)
          if (item) {
            data.jobType = [
              item.remark === 'common' ? 'common' : 'basic',
              data.jobType
            ]
          }
        })
        data.strategy = String(data.strategy)
        data.start = data.taskType.split('-')[0]
        data.end = data.taskType.split('-')[1]
        data.monitorConf = data.monitorConf ? JSON.parse(data.monitorConf) : {}
        data.syncConf = data.syncConf ? JSON.parse(data.syncConf) : {}
        data.syncStatus = !(data.syncStatus == '0')
        data.mappingStatus = !(data.mappingStatus == '0')
        data.monitorStatus = !(data.monitorStatus == '0')
        data.batchStatus = !(data.batchStatus == '0')
        data.typeStatus = !(data.typeStatus == '0')
        if (data.tableTypeMapping) {
          const arr = []
          JSON.parse(data.tableTypeMapping).forEach((f) => {
            arr.push({
              sink: {
                name: f.sink.name,
                table: f.sink.table,
                ...f.sink.dataType
              },
              source: {
                name: f.source.name,
                table: f.source.table,
                ...f.source.dataType
              }
            })
          })
          data.tableTypeMapping = arr
        }
        if (data.dbTypeMapping) {
          data.dbTypeMapping = JSON.parse(data.dbTypeMapping)
        }
        if (data.syncConf) {
          const obj = {}
          Object.keys(data.syncConf).forEach((f) => {
            const newValue = convertToCamelCase(f)
            obj[newValue] = data.syncConf[f]
            delete data.syncConf[f]
          })
          data.syncConf = obj
        }
        that.form = data
      })
    }
  },
  methods: {
    handleClick(type) {
      let nextSwitch = false
      if (type === 'next') {
        this.allForm[this.active]?.forEach((f) => {
          if (ignoreData.includes(f.dataName)) return
          if (this.form[f.dataName] === '') {
            nextSwitch = true
          }
        })
      }
      if (nextSwitch) {
        return this.$mesvcsage.warning('填写完整信息')
      }
      if (this.active === 4 && type === 'next') {
        this.dataFusion(this.form)
        return
      }
      this.active = type === 'next' ? this.active + 1 : this.active - 1
    },
    toSnakeCase(camelCaseStr, char) {
      return camelCaseStr
        .replace(/([a-z])([A-Z])/g, `$1${char}$2`)
        .toLowerCase()
    },
    async dataFusion(form) {
      const data = JSON.parse(JSON.stringify(form))
      console.log(data, '888')

      data.taskTables = JSON.stringify([])
      data.monitorConf = data.monitorStatus
        ? JSON.stringify(data.monitorConf)
        : '{}'
      data.syncConf = data.syncStatus ? JSON.stringify(data.syncConf) : '{}'
      data.taskType = `${data.start}-${data.end}`
      data.syncStatus = data.syncStatus ? 1 : 0
      data.monitorStatus = data.monitorStatus ? 1 : 0
      data.batchStatus = data.batchStatus ? 1 : 0
      data.mappingStatus = data.mappingStatus ? 1 : 0
      data.typeStatus = data.typeStatus ? 1 : 0
      if (data.dbTypeMapping) {
        data.dbTypeMapping.forEach((f) => {
          delete f.levae
        })
        data.dbTypeMapping = JSON.stringify(data.dbTypeMapping)
      }
      if (data.tableTypeMapping) {
        const typeMapping = []
        data.tableTypeMapping.forEach((f) => {
          // delete f.levae;
          typeMapping.push({
            source: {
              table: f.source.table,
              name: f.source.table,
              dataType: {
                typeName: f.source.typeName,
                length: f.source.length,
                precision: f.source.precision,
                scale: f.source.scale,
                timePrecision: f.source.timePrecision,
                nullable: f.sink.nullable
              }
            },
            sink: {
              table: f.sink.table,
              name: f.sink.table,
              dataType: {
                typeName: f.sink.typeName,
                length: f.sink.length,
                precision: f.sink.precision,
                scale: f.sink.scale,
                timePrecision: f.sink.timePrecision,
                nullable: f.sink.nullable
              }
            }
          })
        })
        data.tableTypeMapping = JSON.stringify(typeMapping)
      }
      data.taskTypeScope = Array.isArray(data.taskTypeScope)
        ? data.taskTypeScope.join(',')
        : data.taskTypeScope
      data.jobType = data.jobType[1]
      if (data.syncConf !== '{}') {
        data.syncConf = JSON.parse(data.syncConf)
        const obj = {}
        Object.keys(data.syncConf).forEach((f) => {
          const newValue = this.toSnakeCase(f, '.')
          obj[newValue] = data.syncConf[f]
          delete data.syncConf[f]
        })
        data.syncConf = JSON.stringify(obj)
      }
      if (data.jdbc && data.jdbc.length > 0) {
        data.jdbc.forEach((f) => {
          delete f.sortBySelectList
          delete f.instanceName
          delete f.name
        })
        const conf = {}
        data.jdbc.forEach((f) => {
          let item
          if (data.mapping) {
            item = data.mapping.filter((v) => f.tableName === v.tableName)
          }
          conf[f.tableName] = item
        })
        data.mapping = JSON.stringify(conf)
      } else {
        data.mapping = JSON.stringify({})
      }
      data.batchConf = JSON.stringify(data.jdbc)
      removeValue.forEach((f) => delete data[f])
      const res = this.id
        ? await dataTaskconfedit(data)
        : await dataTaskconfadd(data)
      this.$message.success(res.msg)
      this.$router.push('/database/dataTaskconf')
      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.sync-box {
  width: 70%;
  height: 95%;
  margin: 1% auto 0 auto;
  position: relative;
  padding-top: 20px;

  .buttonBox {
    text-align: right;
    padding: 20px 0;
  }
}

* {
  font-family: alimama, webfont-notdef;
  letter-spacing: 0.5px;
}

::v-deep .el-col {
  display: flex;
  align-items: center;
}

::v-deep .el-form-item {
  margin-bottom: 0 !important;
  padding: 10px 0;
}

::v-deep .el-progress__text {
  display: none;
}
</style>
